﻿package problems.diningphilosophers.philosopherssolution;

import java.util.ArrayList;
import java.util.List;

import problems.BenchmarkSemaphore;
import problems.diningphilosophers.philosophers.AbstractPhilosopher;

public abstract class AbstractDiningPhilosophersSolution
{
    private final List<AbstractPhilosopher> philosophers;
    
    protected AbstractDiningPhilosophersSolution(int nbPhilosophers)
    {
        List<BenchmarkSemaphore> forks = new ArrayList<BenchmarkSemaphore>();
        for (int i = 0; i < nbPhilosophers; i++)
        {
            forks.add(new BenchmarkSemaphore(1));
        }
        philosophers = createPhilosophers(forks);
    }

    private List<AbstractPhilosopher> createPhilosophers(List<BenchmarkSemaphore> forks)
    {
    	List<AbstractPhilosopher> philosophers = new ArrayList<AbstractPhilosopher>();
        for (int i = 0; i < forks.size(); i++)
        {
            philosophers.add(createPhilosopher(forks.get(i), forks.get((i + 1)%(forks.size()-1))));
        }
        return philosophers;
    }
    
    public List<AbstractPhilosopher> getPhilosophers() {
    	return philosophers;
    }

    protected abstract AbstractPhilosopher createPhilosopher(BenchmarkSemaphore leftFork, BenchmarkSemaphore rightFork);
}